package com.share.common.rabbit.MqConfig;

import com.alibaba.fastjson2.JSON;
import com.rabbitmq.client.Channel;
import com.share.common.rabbit.MqConstant.MqConst;
import com.share.common.rabbit.model.CanalSyncMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

@Component
@Slf4j
public class DeadLetterMessageHandler {

    /**
     * 处理Redis同步死信消息
     */
    @RabbitListener(queues = MqConst.QUEUE_DEAD_LETTER)
    public void handleRedisSyncDeadMessage(String message, Channel channel,
                                           @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        try {
            log.info("-----------消息已进入死信队列------------");
            CanalSyncMessage canalSyncMessage = JSON.parseObject(message, CanalSyncMessage.class);
            log.info("处理Redis同步死信消息: {}", canalSyncMessage);

            // 对死信消息进行特殊处理
            // 例如：记录到数据库、发送告警、人工处理等
            handleDeadMessage(canalSyncMessage);

            // 确认死信消息
            channel.basicAck(deliveryTag, false);
            log.info("死信消息处理完成: {}", deliveryTag);

        } catch (Exception e) {
            log.error("处理死信消息失败: {}", message, e);
            try {
                // 死信消息处理失败，记录日志并确认，避免无限重试
                channel.basicAck(deliveryTag, false);
                log.error("死信消息处理失败，已确认避免无限重试: {}", deliveryTag);
            } catch (IOException ioException) {
                log.error("死信消息确认失败: {}", deliveryTag, ioException);
            }
        }
    }

    /**
     * todo 处理死信消息的具体逻辑
     */
    private void handleDeadMessage(CanalSyncMessage canalSyncMessage) {
        // 1. 记录到数据库，供人工处理
        // 2. 发送告警通知
        // 3. 尝试其他补偿机制
        log.warn("消息经过{}次重试仍失败，需要人工介入处理: {}", 50 , canalSyncMessage);
    }

}
